package com.my.programmtic;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

/**
 *  编程式事务管理之命令式 - 通过TransactionTemplate来实现事务管理
 *
 * @author: marshal
 * @date: 2023-05-24 14:45
 */
public class ImperativeTransactionTemplateService {
    private final TransactionTemplate transactionTemplate;

    public ImperativeTransactionTemplateService(PlatformTransactionManager transactionManager) {
        this.transactionTemplate = new TransactionTemplate(transactionManager);
        // 设置隔离级别
        this.transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
        this.transactionTemplate.setTimeout(30); // 30 seconds
    }

    /**
     * 有返回值
     *
     * @return int
     */
    public Integer testTransactionWithCallback() {
        return transactionTemplate.execute(status -> {
            update1();
            update2();
            return 1;
        });
    }

    /**
     * 无返回值
     *
     */
    public void testTransactionWithoutResult() {
        transactionTemplate.executeWithoutResult(status -> {
            update1();
            update2();
        });
    }

    /**
     *  回滚操作
     */
    public void testTransactionRollback() {
        transactionTemplate.executeWithoutResult(status -> {
            try {
                update1();
                update2();
            } catch (Exception ex) {
                // 发生错误时回滚
                status.setRollbackOnly();
            }
        });
    }

    public Integer update1(){
        System.out.println("this is update1");
        return 1;
    }

    public Integer update2() {
        System.out.println("this is update2");
        return 2;
    }
}
